package com.wetsion.securityoauthdemo.rmsclient.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.filter.OAuth2ClientAuthenticationProcessingFilter;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.client.token.AccessTokenProviderChain;
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider;
import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails;
import org.springframework.security.oauth2.common.AuthenticationScheme;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * @author weixin
 * @version 1.0
 * @CLassName Oauth2ClientConfig
 * @date 2019/3/7 6:09 PM
 */
//@Configuration
//@EnableOAuth2Client
public class Oauth2ClientConfig {

    private final static String CHECK_TOKEN_URL = "http://localhost:9001/oauth/check_token";
    private final static String ACESS_TOKEN_URL = "http://localhost:9001/oauth/token";
    private final static String CLIENT_SECRET = "weixin";
    private final static String CLIENT_ID = "rms";
    private final static String USERNAME = "weixin";
    private final static String PASSWORD = "weixin";

    @Bean
    public OAuth2RestTemplate oAuth2RestTemplate(OAuth2ClientContext oAuth2ClientContext, OAuth2ProtectedResourceDetails details) {
        OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(details, oAuth2ClientContext);
//        AuthorizationCodeAccessTokenProvider provider = new AuthorizationCodeAccessTokenProvider();
//        provider.setStateMandatory(false);
//        AccessTokenProviderChain chain = new AccessTokenProviderChain(Arrays.asList(provider));
//        restTemplate.setAccessTokenProvider(chain);
        return restTemplate;
    }

    /**
     * 注册处理redirect uri的filter
     * @param oauth2RestTemplate
     * @param tokenService
     * @return
     */
//    @Bean
//    public OAuth2ClientAuthenticationProcessingFilter oauth2ClientAuthenticationProcessingFilter(
//            OAuth2RestTemplate oauth2RestTemplate,
//            RemoteTokenServices tokenService) {
//        OAuth2ClientAuthenticationProcessingFilter filter
//                = new OAuth2ClientAuthenticationProcessingFilter("/api/**");
//        filter.setRestTemplate(oauth2RestTemplate);
//        filter.setTokenServices(tokenService);
//
//
//        //设置回调成功的页面
////        filter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler() {
////
////            @Override
////            public void onAuthenticationSuccess(HttpServletRequest request,
////                                                HttpServletResponse response,
////                                                Authentication authentication) throws IOException, ServletException {
////                this.setDefaultTargetUrl("/login");
////                super.onAuthenticationSuccess(request, response, authentication);
////            }
////
////        });
//        filter.setAuthenticationSuccessHandler(new CustomSaveRequestSuccessHandler());
//        filter.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler());
//        return filter;
//    }

    /**
     * 注册tokenservice，检查获取token
     **/
    @Bean
    public RemoteTokenServices tokenServices(OAuth2ProtectedResourceDetails details) {
        RemoteTokenServices tokenServices = new RemoteTokenServices();
        tokenServices.setCheckTokenEndpointUrl(CHECK_TOKEN_URL);
        tokenServices.setClientId(details.getClientId());
        tokenServices.setClientSecret(details.getClientSecret());
        return tokenServices;
    }

    @Bean
    public OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails() {
        ResourceOwnerPasswordResourceDetails passwordResourceDetails =
                new ResourceOwnerPasswordResourceDetails();
        passwordResourceDetails.setClientId(CLIENT_ID);
        passwordResourceDetails.setClientSecret(CLIENT_SECRET);
        passwordResourceDetails.setUsername(USERNAME);
        passwordResourceDetails.setPassword(PASSWORD);
        passwordResourceDetails.setAccessTokenUri(ACESS_TOKEN_URL);
        passwordResourceDetails.setClientAuthenticationScheme(AuthenticationScheme.form);
        passwordResourceDetails.setAuthenticationScheme(AuthenticationScheme.none);
        return passwordResourceDetails;
    }
}
